package com.cuckoo.mall.thus.manager;

import android.text.TextUtils;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bgn.baseframe.network.bean.TDataBean;
import com.bgn.baseframe.utils.BaseConstant;
import com.bgn.baseframe.utils.HttpCode;
import com.bgn.baseframe.utils.PreferUtil;
import com.bgn.baseframe.utils.jsontool.GsonUtil;
import com.cuckoo.mall.javabean.UserData;
import com.cuckoo.mall.javabean.UserInfo;
import com.cuckoo.mall.network.ApiManager;
import com.orhanobut.logger.Logger;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * 类描述：
 * 创建人：wl
 * 创建时间：2018/3/22 10:13
 */
public class UserInfoManager {
    /*用户信息类，包含用户资料*/
    private UserInfo userInfo;//ID TOKEN
    /*是否鉴权通过*/
    private boolean isLogin = false;
    /*是否加载用户资料成功*/
    private boolean isLoadUserDataSucceed = false;
    /*Toke Error Type*/
    private int TokenErrorType = -1;

    /*静态内部类，实现懒汉单例*/
    public static UserInfoManager getInstance() {
        return UserInfoManagerHolder.USER_INFO_MANAGER;
    }

    private static class UserInfoManagerHolder {
        private static final UserInfoManager USER_INFO_MANAGER = new UserInfoManager();
    }

    //初始化时读取缓存的用户信息，拿到id和token去鉴权，看是否过期，无效
    private UserInfoManager() {
        userInfo = new UserInfo();
        String cacheUser = PreferUtil.getString(BaseConstant.CACHE_USER_INFO, "");
        if (!TextUtils.isEmpty(cacheUser)) {
            UserInfo user = GsonUtil.fromJson(cacheUser, UserInfo.class);
            if (user != null && !TextUtils.isEmpty(user.getToken()) && user.getUser_id() > 0) {
                authLogin(user);
            } else {
                Logger.d("用户缓存信息异常");
                exitLogin();
            }
        } else {
            Logger.d("无缓存信息");
            exitLogin();
        }
    }

    /*启动时，本地有缓存时，鉴权*/
    public void authLogin(final UserInfo cacheUser) {
        ApiManager.autoLogin(String.valueOf(cacheUser.getUser_id()), cacheUser.getToken()).subscribe(new Observer<TDataBean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(TDataBean value) {
                if (value.isSucceed()) {
                    Logger.d("鉴权成功");
                    loginSucceed(cacheUser);
                } else {
                    //ToastUtil.showInfo(getString(R.string.login_time_out));
                    if (value.getCode() == HttpCode.TOKEN_OUT_DATE || value.getCode() == HttpCode.TOKEN_ERROR) {
                        TokenErrorType = value.getCode();
                    }
                    exitLogin();
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });

    }

    /*登录成功处理用户信息*/
    public void loginSucceed(UserInfo userInfoResult) {
        PreferUtil.putString(BaseConstant.CACHE_USER_INFO, GsonUtil.toJson(userInfoResult));
        userInfo = userInfoResult;
        isLogin = true;

        /*登录或者鉴权成功再去拉去用户资料*/
        getUserData();
    }

    public void getUserData() {
        ApiManager.getUserData().subscribe(new Observer<TDataBean<UserData>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(TDataBean<UserData> value) {
                if (value.isSucceed()) {
                    updateUserData(value.getData());
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    public void exitLogin() {
        isLogin = false;
        PreferUtil.putString(BaseConstant.CACHE_USER_INFO, "");
        userInfo = new UserInfo();
       // Freshchat.resetUser(UiUtil.getContext());
    }

    public boolean isLogin() {
        return isLogin;
    }

    public boolean isLoadUserDataSucceed() {
        return isLoadUserDataSucceed;
    }

    public UserInfo getUserInfo() {
        return userInfo;
    }

    public void updateUserData(UserData userData) {
        userInfo.setData(userData);
        isLoadUserDataSucceed = true;
        PreferUtil.putString(BaseConstant.CACHE_USER_INFO, GsonUtil.toJson(userInfo));
        //setFreshchat(userData);
    }

//    private void setFreshchat(UserData userData) {
//        //        /*处理freshchate用户资料*/
//        FreshchatUser freshUser = Freshchat.getInstance(getContext()).getUser();
//        freshUser.setFirstName(userData.getNick_name());
//        freshUser.setLastName("");
//        freshUser.setEmail(userData.getEmail());
//        freshUser.setPhone("+86", userData.getPhone());
//        Freshchat.getInstance(getContext()).setUser(freshUser);
//        Freshchat.getInstance(getContext()).setUserProperty("id", String.valueOf(userInfo.getUser_id()));
//        String token = FirebaseInstanceId.getInstance().getToken();
//        Freshchat.getInstance(getContext()).setPushRegistrationToken(token);
//    }


    public boolean checkTrunLogin() {
        if (isLogin) {
            return true;
        } else {
            // ToastUtil.showInfo(UiUtil.getString(R.string.not_log_in_tip));
            ARouter.getInstance().build("/mall/loginActivity").navigation();
            return false;
        }
    }

    public int getTokenErrorType() {
        return TokenErrorType;
    }
}
